// packageA/pages/smart-home/index.js
const App = getApp();
let dictList = JSON.parse(JSON.stringify(App.globalData.dictTree));
const WXAPI = require("../../api/org");
const baseUrl = require("../../../api/config").dev; //这里用的是ES6的写法
var amapFile = require("../../../libs/amap-wx.130 2.js"); //如：..­/..­/libs/amap-wx.js
import config from "../../../config";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isFromHomeSearch: "0",
    currentInfo: {},
    latitude: "31.836436",
    longitude: "117.138433",
    isList: true,
    areaInfoSelected: {
      provinceObj: {
        sCode: "340000",
        sName: "安徽省",
      },
      cityObj: {
        sCode: "",
        sName: "",
      },
      areaObj: {
        sCode: "",
        sName: "",
      },
      streetObj: {
        sCode: "",
        sName: "",
      },
      villageObj: {
        sCode: "",
        sName: "",
      },
    },
    isShowAddress: true,
    distance: [
      {
        value: 1.5,
        selected: false,
      },
      {
        value: 5,
        selected: false,
      },
      {
        value: 10,
        selected: false,
      },
      {
        value: 20,
        selected: false,
      },
      {
        value: 50,
        selected: false,
      },
      {
        value: 100,
        selected: false,
      },
    ],
    areaTitle: "安徽省",
    imgBaseUrl: `${baseUrl["imgBaseUrl"]}`,
    currentPageNum: 1,
    form: {
      PageIndex: 1,
      PageSize: 20,
      dLongDistanc: "",
      sProvinceCode: "340000",
    },
    isShow: false,
    listIsOver: false,
    isLoading: false,
    option1: [],
    option2: [],
    option3: [],
    list: [],
    crossAxisCount: 2,
    crossAxisGap: 10,
    mainAxisGap: 10,
  },
  changePage() {
    this.setData({
      isList: !this.data.isList,
    });
    this.getList();
  },
  addMarkers(arr) {
    const marker = {
      id: 1,
      iconPath:
        "https://develop.wx.365yiyang.com/pubapi/files/appletstaticimg/position.png",
      width: 31,
      height: 40,
      joinCluster: false, // 指定了该参数才会参与聚合
      label: {
        fontSize: 12,
        // borderWidth: 1,
        padding: 6,
        borderRadius: 15,
        bgColor: "#ffffff",
        textAlign: "center",
        anchorX: "-50",
        anchorY: -75,
      },
    };
    const positions = [];
    for (let i = 0; i < arr.length; i++) {
      positions.push({
        latitude: arr[i].dTencentLat,
        longitude: arr[i].dTencentLng,
        text: arr[i].sServiceOrgName,
        sid: arr[i].sId,
        orgId: arr[i].sOrgId,
      });
    }

    const markers = [];
    positions.forEach((p, i) => {
      marker.label.anchorX = -((p.text.length / 2) * 12);
      const newMarker = Object.assign(marker, p);
      newMarker.id = i + 1;
      newMarker.orgId = p.orgId;
      newMarker.label.content = p.text;
      markers.push(newMarker);
      this.mapCtx.addMarkers({
        markers,
        clear: false,
        complete(res) {
          console.log("addMarkers", res);
        },
      });
    });
    this.setData({
      markers: markers,
    });
    // this.setData({
    //   currentInfo: markers[0]
    // });
  },
  removeMarkers() {
    this.mapCtx.addMarkers({
      clear: true,
      markers: [],
    });
  },
  onMarkerTap(e) {
    this.setData({
      currentInfo: this.data.markers[e.detail.markerId - 1],
    });
    const { text, sid, orgId } = this.data.currentInfo;
    wx.navigateTo({
      url: `/packageA/pages/org-detail/index?orgId=${orgId}&id=${sid}&title=${text}`,
    });
  },
  toOrgDetail(e) {
    const { id, orgid, title } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/packageA/pages/org-detail/index?orgId=${orgid}&id=${id}&title=${title}`,
    });
  },
  onCalloutTap(e) {
    console.log("@@ onCalloutTap", e);
  },
  onLabelTap(e) {
    console.log("@@ labletap", e);
    this.setData({
      currentInfo: this.data.markers[e.detail.markerId - 1],
    });
    const { text, sid, orgId } = this.data.currentInfo;
    debugger;
    wx.navigateTo({
      url: `/packageA/pages/org-detail/index?orgId=${orgId}&id=${sid}&title=${text}`,
    });
  },
  open() {
    this.setData({
      isShowAddress: true,
    });
  },
  selecteItem1(e) {
    const { value } = e.currentTarget.dataset;
    let distance = this.data.distance;
    for (let i = 0; i < distance.length; i++) {
      if (distance[i].value == value) {
        distance[i].selected = !distance[i].selected;
      } else {
        distance[i].selected = false;
      }
    }
    let res = distance.filter((item) => {
      return item.selected;
    });
    if (res && res.length > 0) {
      this.setData({
        "form.dLongDistanc": res[0].value,
      });
    } else {
      this.setData({
        "form.dLongDistanc": "",
      });
    }
    this.setData({
      distance,
    });
  },
  selecteItem2(e) {
    const { value } = e.currentTarget.dataset;
    let option3 = this.data.option3;
    for (let i = 0; i < option3.length; i++) {
      if (option3[i].value == value) {
        option3[i].selected = !option3[i].selected;
      } else {
        option3[i].selected = false;
      }
    }
    let res = option3.filter((item) => {
      return item.selected;
    });
    if (res && res.length > 0) {
      this.setData({
        "form.sOrgNatureCode": res[0].value,
      });
    } else {
      this.setData({
        "form.sOrgNatureCode": "",
      });
    }
    this.setData({
      option3,
    });
  },
  sureAddress(e) {
    console.log("e", e);
    const {
      sProvinceCode,
      sCityCode,
      sCountryCode,
      sStreetCode,
      sCommunityCode,
    } = e.detail.obj;
    const address = e.detail.fullArea;
    this.setData({
      "form.sProvinceCode": sProvinceCode,
      "form.sCityCode": sCityCode,
      "form.sCountryCode": sCountryCode,
      "form.sStreetCode": sStreetCode,
      "form.sCommunityCode": sCommunityCode,
      areaTitle: address,
    });
    this.selectComponent("#item1").toggle();
    this.getList();
  },
  cancelAddress() {
    this.selectComponent("#item1").toggle();
  },
  reset() {
    let res1 = this.data.distance;
    let res2 = this.data.option3;
    res1.map((i) => (i.selected = false));
    res2.map((i) => (i.selected = false));
    this.setData({
      distance: res1,
      option3: res2,
      isShow: false,
      areaTitle: "安徽省",
      form: {
        PageIndex: 1,
        PageSize: 20,
        sProvinceCode: "340000",
      },
    });
    this.selectComponent("#item2").toggle();
  },
  onConfirm() {
    this.getList();
    this.selectComponent("#item2").toggle();
  },
  changeOptions1(e) {
    this.setData({
      "form.iMinBedTatol": e.detail == "0" ? "" : e.detail.split("-")[0],
      "form.iMaxBedTatol": e.detail == "0" ? "" : e.detail.split("-")[1],
    });
    this.getList();
  },
  changeOptions2(e) {
    console.log('e',e);
    this.setData({
      "form.dMinFee": e.detail == "0" ? "" : e.detail.split("-")[0],
      "form.dMaxFee": e.detail == "0" ? "" : (e.detail.split("-")[1] || ''),
    });
    this.getList();
  },
  search(e) {
    this.setData({
      form: {
        ...this.data.form,
        sOrgName: e.detail.keyWords,
      },
    });
    this.getList();
  },
  openFilter() {
    this.setData({
      isShow: !this.data.isShow,
    });
    if (!this.data.isShow) {
      this.selectComponent("#item2").toggle(false);
      this.selectComponent("#item1").toggle(false);
      this.selectComponent("#dropItem2").toggle(false);
      this.selectComponent("#dropItem3").toggle(false);
    }
    if(this.data.isShowAddress){
      this.setData({
        isShowAddress:false
      })
    }
  },
  formatOptions(arr) {
    let newArr = [
      {
        text: "全部",
        value: "0",
      },
    ];
    arr.map((item) => {
      newArr.push({
        text: item.sName,
        value: item.sValue,
      });
    });
    return newArr;
  },
  async getList() {
    this.setData({
      listIsOver: false,
      isLoading: true,
    });
    let isCustomLoading = true;
    let res = await WXAPI.getOrgList(this.data.form, isCustomLoading);
    let listArr = [];
    if (res.data.code == 0) {
      if (this.data.form.PageIndex == 1) {
        listArr = res.data.data.list;
        if (listArr && listArr.length > 0) {
          for (let i = 0; i < listArr.length; i++) {
            listArr[i].imgUrl =
              this.data.imgBaseUrl + listArr[i].sDoorheadPhoto;
          }
        }
      } else {
        listArr = this.data.serviceList;
        for (let i = 0; i < res.data.data.list.length; i++) {
          listArr[i].imgUrl =
            this.data.imgBaseUrl + res.data.data.list[i].sDoorheadPhoto;
        }
        Array.prototype.push.apply(listArr, res.data.data.list);
      }
      this.setData({
        listIsOver: true,
      });
      // 绘制标注点
      this.removeMarkers();
      this.addMarkers(listArr);
      this.setData({
        list: listArr,
        triggered: false,
        currentPageNum: res.data.data.list.length,
        isLoading: false,
      });
    }
  },
  onClickHide() {
    this.setData({
      isShow: false,
    });
  },
  //上拉触底
  onScrollBottom() {
    if (this.data.form.PageIndex < this.data.currentPageNum) {
      this.setData({
        "form.PageIndex": this.data.form.PageIndex + 1,
      });
      this.getList();
    } else if (
      this.data.form.PageIndex > this.data.currentPageNum ||
      this.data.form.PageIndex == this.data.currentPageNum
    ) {
      this.setData({
        listIsOver: true,
      });
    }
  },
  //下拉刷新
  async onRefresh() {
    this.setData({
      "form.PageIndex": 1,
      list: [],
    });
    this.getList();
  },
  getPosition() {
    var myAmapFun = new amapFile.AMapWX({
      key: config.gdMapKey,
    });
    let _this = this;
    myAmapFun.getRegeo({
      success: function (data) {
        //成功回调
        _this.setData({
          // currentCity: data[0].regeocodeData.addressComponent.district,
          "form.dLat": data[0].latitude,
          "form.dLng": data[0].longitude,
          latitude: data[0].latitude,
          longitude: data[0].longitude,
        });
        _this.getList();
      },
      fail: function (info) {
        //失败回调
        console.log(info);
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.keyWords) {
      this.setData({
        "form.sOrgName": options.keyWords,
      });
    }
    if (options.isFromHomeSearch) {
      this.setData({
        isFromHomeSearch: options.isFromHomeSearch,
      });
    }
    this.mapCtx = wx.createMapContext("mapId");
    this.mapCtx.on("markerClusterClick", (res) => {
      console.log("markerClusterClick", res);
    });

    // 初始化筛选项下拉数据格式
    this.setData({
      option1: this.formatOptions(
        dictList.filter((item) => item.sValue == "SearchOrgBedNums")[0].Child
      ),
      option2: this.formatOptions(
        dictList.filter((item) => item.sValue == "SearchOrgFee")[0].Child
      ),
      option3: this.formatOptions(
        dictList.filter((item) => item.sValue == "OrgInstitutionalNature")[0]
          .Child
      ),
    });
    // 获取当前经纬度
    this.getPosition();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    if (this.data.isFromHomeSearch == "1") {
      let pages = getCurrentPages(); //获取当前页面pages里的所有信息。
      let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。
      prevPage.setData({
        // 将我们想要传递的参数在这里直接setData。上个页面就会执行这里的操作。
        searchValue: this.data.form.sOrgName,
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      "form.PageIndex": 1,
      list: [],
    });
    this.getList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
